#!/bin/sh

#
# Test the MBR creation ability of fwup
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
# Numbers don't matter for the test so long as the MBR is right
define(BOOT_PART_OFFSET, 1024)
define(BOOT_PART_COUNT, 1024)
define(ROOTFS_A_PART_OFFSET, 2048)
define(ROOTFS_A_PART_COUNT, 2048)
define(ROOTFS_B_PART_OFFSET, 4096)
define(ROOTFS_B_PART_COUNT, 2048)
define(APP_PART_OFFSET, 8192)
define(APP_PART_COUNT, 4096)
# define(APP_PART_COUNT, 12288) # expanded size

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
    partition 1 {
        block-offset = \${ROOTFS_A_PART_OFFSET}
        block-count = \${ROOTFS_A_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 2 {
        block-offset = \${ROOTFS_B_PART_OFFSET}
        block-count = \${ROOTFS_B_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 3 {
        block-offset = \${APP_PART_OFFSET}
        block-count = \${APP_PART_COUNT}
        type = 0x83 # Linux
        expand = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
        }
}
EOF

# This is an unexpanded result
base64_decode >$WORK/unexpanded.img <<EOF
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAggMAg0YFAQAgAAAAMAAAVao=
EOF


# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

# Check that when creating a file and there's no size information that
# the partition will be the specified block_size
cmp_bytes 512 $WORK/unexpanded.img $IMGFILE

# Repeat the test, but specify a max size so that the final partition is larger
rm $IMGFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE --max-size=20480 -t complete
cmp_bytes 512 $WORK/expanded.img $IMGFILE

# Repeat the test, but now apply to a large regular file. This is a common qemu
# use case.
rm $IMGFILE
dd if=/dev/zero of=$IMGFILE seek=20480 count=0
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete
cmp_bytes 512 $WORK/expanded.img $IMGFILE

# Repeat the test, but check that --max-size overrides existing file size
rm $IMGFILE
dd if=/dev/zero of=$IMGFILE seek=19480 count=0
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE --max-size=20480 -t complete
cmp_bytes 512 $WORK/expanded.img $IMGFILE

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
